"""
主题: 通过字符串调用对象方法
问题: 你有一个字符串形式的方法名称，想通过它调用某个对象的对应方法。
提示 : 
"""

import math
import operator

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        # !r表示调用后面参数的__repr__()方法
        return 'Point({!r:},{!r:})'.format(self.x, self.y)

    def distance(self, x, y):
        return math.hypot(self.x - x, self.y - y)

def recipe1():
    p = Point(2, 3)
    print(f"{getattr(p, 'distance')(0, 0) = }")  # Calls p.distance(0, 0)

def recipe2():
    p = Point(2, 3)
    print(f"{operator.methodcaller('distance', 0, 0)(p) = }")

def recipe3():
    points = [
        Point(1, 2),
        Point(3, 0),
        Point(10, -3),
        Point(-5, -7),
        Point(-1, 8),
        Point(3, 2)
    ]
    # Sort by distance from origin (0, 0)
    points.sort(key=operator.methodcaller('distance', 0, 0))
    print(f"{points = }")

def recipe4():
    p = Point(3, 4)
    d = operator.methodcaller('distance', 0, 0)
    print(f"{d(p) = }")

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()
    print('recipe4'.center(20, '*'))
    recipe4()

if __name__ == '__main__':
    main()            